package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"regexp"
	"strings"
)

// 请求头结构体
type Data struct {
	Path    string `json:"path"`
	Account string `json:"account"`
}

type JsonHeader struct {
	Action    string `json:"action"`
	Data      Data   `json:"data"`
	SessionId string `json:"sessionId"`
}

// 返回值结构体
type ServiceNums struct {
	ServiceNum      string `json:"serviceNum"`
	IncludeHolidays []interface{}
	Ael             string `json:"ael"`
}

type Result struct {
	ServiceNums []ServiceNums
	StartDate   string `json:"startDate"`
	EndDate     string `json:"endDate"`
}

type Results struct {
	Success bool
	Message string `json:"message"`
	Result  Result `json:"result"`
}

func RequestData(sessionid string, url string, path string, account string) []byte {
	ReqJson := &JsonHeader{
		Action: "config.ivr.holiday.syncHolidayAel",
		Data: Data{
			Path:    path,
			Account: account,
		},
		SessionId: sessionid,
	}
	b, _ := json.Marshal(ReqJson)
	log.Printf("request %s %s\n", url, string(b))

	reader := bytes.NewReader(b)
	req, err := http.NewRequest("POST", url, reader)
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
	return body

}

func DealData(path string, account string, b []byte) {
	var results Results
	if err := json.Unmarshal(b, &results); err != nil {
		log.Fatal(err)
		return
	}
	for i := 0; i < len(results.Result.ServiceNums); i++ {
		filename := path + "/account/" + results.Result.ServiceNums[i].ServiceNum + "-dayoff.ael"
		message := results.Result.ServiceNums[i].Ael
		f, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0666)
		if err != nil {
			log.Fatal("open file error: ", err)
			return
		}
		defer f.Close()
		_, err = f.WriteString(message)
		if err != nil {
			log.Fatal(err)
			return
		}
	}
}

const (
	url       = "https://test.simpleconnect.jp/setting"
	sessionid = "e88426b0-8a34-11ec-b5a7-f3f94300c7e0"
	basepath  = "/etc/asterisk/"
)

func SearchAstProcess() []string {
	cmdStr := fmt.Sprintf("ps aux|grep asterisk|grep conf|grep -v gateway|grep -v grep|awk '{print $NF}'|awk -F '/' '{print $(4)}'")
	cmd := exec.Command("/bin/bash", "-c", cmdStr)
	out, _ := cmd.StdoutPipe()
	if err := cmd.Start(); err != nil {
		log.Fatal(err)
	}
	Bytes, err := ioutil.ReadAll(out)
	if err != nil {
		log.Fatal(err)
	}
	//fmt.Println(string(Bytes))
	var line = strings.Split(string(Bytes), "\n")
	var asterisks []string
	for _, st := range line {
		asterisks = append(asterisks, st)
	}
	fmt.Println(asterisks)
	return asterisks
}

func SearchAccount(basepath string, ast string) []string {
	cmdStr := fmt.Sprintf("ls %s", basepath+ast+"/accounts")
	cmd := exec.Command("/bin/bash", "-c", cmdStr)
	out, _ := cmd.StdoutPipe()
	if err := cmd.Start(); err != nil {
		log.Fatal(err)
	}
	Bytes, err := ioutil.ReadAll(out)
	if err != nil {
		log.Fatal(err)
	}
	var line = strings.Split(string(Bytes), "\n")
	var accounts []string
	re, _ := regexp.Compile(`^N0000`)
	for _, st := range line {
		if re.MatchString(st) {
			accounts = append(accounts, st)
		}
	}
	return accounts
}

func main() {
	for _, instance := range SearchAstProcess() { // ps命令筛选进程获得asterisk实例
		if instance != "" {
			accounts := SearchAccount(basepath, instance) // ls /etc/asterisk/${instance}/ 获得账户数组
			path := basepath + instance                   // path = /etc/asterisk/${instance}
			//fmt.Println(accounts)
			for _, account := range accounts {
				body := RequestData(sessionid, url, path+"/accounts", account) // 获取接口返回值
				DealData(path, account, body)                                  // 写入ael文件
			}
		}
	}
}
